import os
import sys
import re
import shutil
from PyQt4 import QtCore, QtGui, Qt
import time
import record_adder

class RecordWindow(QtGui.QDialog):
    '''
    A dialog widget used for the indexing window. Subclassed for its close event.
    '''
    def __init__(self, parent = None):
        QtGui.QDialog.__init__(self, parent)
        self.record_dialog = record_adder.Ui_Dialog()
        self.record_dialog.setupUi(self)
        self.record_dialog.online_details_button.clicked.connect(self.get_online_info)
        self.downloading = False
        self.connect(self.record_dialog.saveButton, QtCore.SIGNAL('clicked()'),
                     self.save_file)
        self.connect(self.record_dialog.pushButton, QtCore.SIGNAL('clicked()'),
                     self.save_pdf_file)

    def set_save_filename(self, eid_val, filename, config_dict):
        self.save_filename = filename
        self.config_dict = config_dict
        self.eid_val = eid_val
        self.pdf_file = self.save_filename[:-3] + 'pdf'

    def clear_fields(self):
        self.detail = {}
        details_titles = ['Title', 'Authors', 'Year', 'Journal', 'Issue',
                          'Pages', 'Tags']
        for i in details_titles:
            self.detail[i] = ''
        self.detail['ScopusRecord'] = ''
        self.detail['ArticleLink'] = ''
        try:
            for i in details_titles:
                eval('self.record_dialog.%s_lineEdit.clear()' % i)
        except:
            pass
            
    def update_info(self):
        details_titles = ['Title', 'Authors', 'Year', 'Journal', 'Issue', 'Pages', 'Tags']
        try:
            self.detail = eval(open(self.save_filename).read())
            for i in details_titles:
                eval('self.record_dialog.%s_lineEdit.setText("%s")' % (i, self.detail[i]))
        except:
            self.record_dialog.Title_lineEdit.setText("Not a saved record. You can either edit saved records or add new records here.")
            for i in details_titles[1:]:
                eval('self.record_dialog.%s_lineEdit.setText("")' % i)
        
            
    def get_online_info(self):
        title_text = str(self.record_dialog.title_input_lineEdit.text()).strip()
        doi_text = str(self.record_dialog.doi_lineEdit.text()).strip()
        if (title_text == "") and (doi_text == ""):
            QtGui.QMessageBox.warning (self, 'Any search term',
                                           'Either article "doi" or a "title" is needed to get the info.',
                                           QtGui.QMessageBox.Ok)
            return
        if doi_text:
            self.get_doi_details(doi_text)
            return
        if title_text:
            self.get_title_details(title_text)
            return
        
    def get_doi_details(self, doi_val):
        try:
            import common_tools
            br = common_tools.setup_browser()
            br.open('http://misshie.jp/doi2bibtex/')
            br.select_form(nr=0)
            br['id'] = doi_val
            page = br.submit()
            self.populate_doi_text(page.read())
        except:
            self.error_warning()

    def populate_doi_text(self, text):
        detail_split = text.split('<br>')[1:-2]
        detail_split = [y.strip() for y in detail_split]
        detail_val_re = re.compile("{(.*?)}")
        detail_val = []
        for i in detail_split:
            detail_val.append(detail_val_re.findall(i))
        
        detail_keys = ['Authors', 'Title', 'Journal', 'Year', 'Issue', 'number', 'Pages']
        details = dict(zip(detail_keys, detail_val))
        if details['Title'][0].strip() == '':
            self.error_warning()
            return
        #Change volume by adding number to it
        details['Issue'] = [details['Issue'][0] + '(' + details['number'][0] + ')']
        for i in detail_keys:
            try:
                eval('self.record_dialog.%s_lineEdit.setText("%s")' % (i, details[i][0]))
            except:
                pass
        
    def get_title_details(self, title):
        import common_tools
        br = common_tools.setup_browser()
        title = '+'.join(title.split())
        google_scholar_url = 'http://scholar.google.com/scholar?q=' + title
        page = br.open(google_scholar_url)
        detail_val_re = re.compile('<span\s*class=gs_a>(.*?)</span>')
        detail_val = detail_val_re.findall(page.read())[0]
        details = detail_val.split('-')
        detail_val = [y.strip() for y in details]
        details = {}
        details['Authors'] = detail_val[0]
        details['Journal'], details['Year'] = detail_val[1].split(',')
        for i in details:
            try:
                eval('self.record_dialog.%s_lineEdit.setText("%s")' % (i, details[i]))
            except:
                pass

                
    def error_warning(self):
        QtGui.QMessageBox.warning (self, 'Retrieval issues',
                                   'Details cannot be found.\nTry manually entering the information.',
                                   QtGui.QMessageBox.Ok)

    def save_pdf_file(self):
        local_pdf_filename = QtGui.QFileDialog.getOpenFileName(self,
                                                         "Open a pdf file for this record.",
                                                         "",
                                                         "*.pdf")
        if local_pdf_filename == '':
            return
        import pdf_downloader
        shutil.copyfile(local_pdf_filename, self.pdf_file)
        f = pdf_downloader.convert_pdf_to_text(self.pdf_file, self.config_dict)
        while f: pass
        
    def save_file(self):
        if not os.path.isfile(self.pdf_file):
            QtGui.QMessageBox.warning (self, 'Pdf file not found',
                                   'You need to add a pdf file for this record.',
                                   QtGui.QMessageBox.Ok)
            return
        #Check at least these
        details_titles = ['Title', 'Authors', 'Year', 'Journal']
        for i in details_titles:
            vals = str(eval('self.record_dialog.%s_lineEdit.text()' % i)).strip()
            if vals == '':
                QtGui.QMessageBox.warning (self, '%s not found' % i,
                                   'You need to add %s for this record.' % i,
                                   QtGui.QMessageBox.Ok)
                return
        details_titles = ['Title', 'Authors', 'Year', 'Journal', 'Issue',
                          'Pages', 'Tags']
        for i in details_titles:
            vals = str(eval('self.record_dialog.%s_lineEdit.text()' % i)).strip()
            vals = ' '.join(vals.split())
            vals = vals.replace('\n', ' ')
            self.detail[i] = vals
        self.detail['EID'] = self.eid_val
        f = open('%s%s.dxt' % (self.config_dict['storageLocation'], self.eid_val), 'w')
        f.write(repr(self.detail)); f.close()
        self.emit(QtCore.SIGNAL('recordChanged'), self.eid_val)
        
if __name__ == "__main__":
    app = QtGui.QApplication(sys.argv)
    myapp = RecordWindow()
    myapp.show()
    sys.exit(app.exec_())


